<?php

namespace App\Http\Controllers\Course;

use App\Events\Collect;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CollectController extends BaseController
{
    public function index()
    {

    }


    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'course_id' => 'required|integer'
        ]);
        $user_id = auth('api')->id();
        $status = DB::table('user_collect_courses')
                    ->where([
                        'user_id' => $user_id,
                        'course_id' => $param['course_id']
                    ])->value('status');


        if (empty($status) || $status==1){
            event(new Collect($user_id));
        }

        if (empty($status)){
            $result =  DB::table('user_collect_courses')->insert([
                'user_id' => $user_id,
                'course_id' => $param['course_id'],
                'status' => 1,
                'collect_time' => date('Y-m-d H:i:s')
            ]);
            return $result ? $this->success() :$this->error();
        }

        $status = $status==1 ? 2 : 1;
        $result = DB::table('user_collect_courses')->where([
            'user_id' => $user_id,
            'course_id' => $param['course_id']
        ])->update(['status' => $status,'collect_time' => date('Y-m-d H:i:s')]);



        return $result ? $this->success() :$this->error();

    }


}
